<template>
  <div class="certificate-container">
    <a-space direction="vertical" :size="8">
      <!-- 查询区 -->
      <div class="search-form">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="开户机构">
            <a-select
              v-model:value="searchForm.institution"
              placeholder="请选择开户机构"
              style="width: 200px"
              allow-clear
              size="small"
            >
              <a-select-option v-for="option in institutionOptions" :key="option.value" :value="option.value">
                {{ option.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="handleSearch" size="small">
                查询
              </a-button>
              <a-button @click="handleReset" size="small">
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>





      <!-- 证书列表 -->
      <a-card title="查询列表" :bordered="false" style="box-shadow: none" :head-style="{ boxShadow: 'none', padding: 0 }" :body-style="{ boxShadow: 'none', padding: 0 }">
        <template #extra>
          <a-button type="primary" @click="handleAdd" size="small">
            新增
          </a-button>
        </template>



        <a-table
          :columns="columns"
          :data-source="certificateList"
          :pagination="pagination"
          :loading="loading"
          row-key="id"
          size="small"
          bordered
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record, index }">
            <!-- 序号列 -->
            <template v-if="column.key === 'index'">
              {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
            </template>

            <!-- 开户机构 -->
            <template v-else-if="column.key === 'acctInstitution'">
              {{ getInstitutionLabel(record.acctInstitution) }}
            </template>

            <!-- 账户分类 -->
            <template v-else-if="column.key === 'acctType'">
              <a-tag :color="record.acctType === 1 ? 'blue' : 'green'">
                {{ getAccountTypeLabel(record.acctType) }}
              </a-tag>
            </template>

            <!-- 数据状态 -->
            <template v-else-if="column.key === 'dataStatus'">
              <a-tag :color="record.dataStatus === 1 ? 'green' : 'red'">
                {{ getDataStatusLabel(record.dataStatus) }}
              </a-tag>
            </template>

            <!-- 操作列 -->
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button size="small" type="link" @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-button size="small" type="link" danger @click="handleDelete(record)">
                  删除
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-space>

    <!-- 新增/编辑弹窗 -->
    <certificate-form-modal
      :visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      :form-data="formData"
      :institution-options="institutionOptions"
      :is-edit-mode="isEditMode"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      @update:visible="(val) => modalVisible = val"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

import { message, Modal } from 'ant-design-vue'
import { useCertificateStore } from './store/index.js'
import { INSTITUTION_OPTIONS } from './api/index.js'
import { ACCOUNT_TYPE_LABELS, DATA_STATUS_LABELS, PAGE_SIZE, TABLE_COLUMNS, MOCK_DATA } from './constants/index.js'
import CertificateFormModal from './components/certificate-form-modal.vue'

const certificateStore = useCertificateStore()

// 搜索表单
const searchForm = reactive({
  institution: ''
})

// 弹窗相关
const modalVisible = ref(false)
const modalLoading = ref(false)
const isEditMode = ref(false)
const formRef = ref()

// 表单数据
const formData = reactive({
  id: null,
  acctInstitution: '',
  acctType: null,
  certificateId: '',
  remark: ''
})



// 表格列配置
const columns = TABLE_COLUMNS

// 计算属性
const certificateList = computed(() => certificateStore.certificateList)
const pagination = computed(() => certificateStore.pagination)
const loading = computed(() => certificateStore.loading)
const institutionOptions = ref(INSTITUTION_OPTIONS)

const modalTitle = computed(() => isEditMode.value ? '编辑证书' : '新增证书')

// 模拟数据
const mockData = MOCK_DATA

// 生命周期
onMounted(() => {
  loadCertificateList()
})

// 加载证书列表
const loadCertificateList = async () => {
  certificateStore.setLoading(true)

  // 模拟异步请求
  setTimeout(() => {
    const filteredData = mockData.filter(item =>
      !searchForm.institution || item.acctInstitution === searchForm.institution
    )

    certificateStore.setCertificateList(filteredData)
    certificateStore.setPagination({
      current: 1,
      pageSize: PAGE_SIZE,
      total: filteredData.length
    })
    certificateStore.setLoading(false)
  }, 500)
}

// 搜索处理
const handleSearch = () => {
  certificateStore.setPagination({ current: 1 })
  loadCertificateList()
}

// 重置搜索条件
const handleReset = () => {
  searchForm.institution = ''
  handleSearch()
}

// 分页变化处理
const handleTableChange = (pag) => {
  certificateStore.setPagination({
    current: pag.current,
    pageSize: pag.pageSize
  })
  loadCertificateList()
}

// 新增操作
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  modalVisible.value = true
}

// 编辑操作
const handleEdit = (record) => {
  isEditMode.value = true
  Object.assign(formData, record)
  modalVisible.value = true
}

// 删除操作
const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除证书 "${getInstitutionLabel(record.acctInstitution)} - ${record.certificateId}" 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      // 模拟删除操作
      const newData = certificateList.value.filter(item => item.id !== record.id)
      certificateStore.setCertificateList(newData)
      certificateStore.setPagination({
        total: newData.length
      })
      message.success('删除成功')
    }
  })
}

// 弹窗确认
const handleModalOk = async () => {
  // 唯一性校验
  if (!await checkUnique()) {
    return
  }

  modalLoading.value = true

  // 模拟保存操作
  setTimeout(() => {
    if (isEditMode.value) {
      // 编辑逻辑
      const index = certificateList.value.findIndex(item => item.id === formData.id)
      if (index !== -1) {
        const updatedItem = {
          ...certificateList.value[index],
          certificateId: formData.certificateId,
          remark: formData.remark,
          updatedBy: 'admin',
          updatedDate: new Date().toISOString()
        }
        const newList = [...certificateList.value]
        newList[index] = updatedItem
        certificateStore.setCertificateList(newList)
      }
      message.success('编辑成功')
    } else {
      // 新增逻辑
      const newItem = {
        id: Date.now(),
        ...formData,
        dataStatus: 1,
        createdBy: 'admin',
        createdDate: new Date().toISOString(),
        updatedBy: 'admin',
        updatedDate: new Date().toISOString()
      }
      certificateStore.setCertificateList([...certificateList.value, newItem])
      certificateStore.setPagination({
        total: certificateList.value.length + 1
      })
      message.success('新增成功')
    }

    modalVisible.value = false
    modalLoading.value = false
  }, 500)
}

// 弹窗取消
const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    acctInstitution: '',
    acctType: null,
    certificateId: '',
    remark: ''
  })
}

// 唯一性校验
const checkUnique = () => {
  const { acctInstitution, acctType, certificateId, id } = formData

  const exists = certificateList.value.some(item =>
    item.acctInstitution === acctInstitution &&
    item.acctType === acctType &&
    item.certificateId === certificateId &&
    item.id !== id
  )

  if (exists) {
    message.error('开户机构 + 账户分类 + 证书ID 组合已存在，请重新输入')
    return false
  }

  return true
}

// 获取开户机构标签
const getInstitutionLabel = (value) => {
  const option = institutionOptions.value.find(opt => opt.value === value)
  return option ? option.label : value
}

// 获取账户分类标签
const getAccountTypeLabel = (type) => {
  return ACCOUNT_TYPE_LABELS[type] || type
}

// 获取数据状态标签
const getDataStatusLabel = (status) => {
  return DATA_STATUS_LABELS[status] || status
}
</script>

<style scoped></style>
